package com.css.apps.base.common.util;

import java.util.List;

import com.css.apps.base.common.provider.UserQueryProvider;
import com.css.apps.base.menu.service.MenuProvider;
import com.css.core.model.IUser;
import com.css.db.config.ConfigurationManager;
import com.css.util.StringHelper;
import com.css.webbase.menu.MenuItem;
public class MenuUtilService {
//缓存内容
private static String cacheName = "_user_menu_content_cache/";
/**
 * 获取用户菜单项
 * @return
 */
public  List<MenuItem>  getUserMenu(){
    List<MenuItem> menus=MenuProvider.getCurrentUserMenu();
   	return menus;
}

public static String  getUserMenuContent(String menuId){
	  cacheName += "_"+menuId;
	 String menuContent = getCachedMenuContent();
	 if(menuContent!=null)return menuContent;	
	 // 获得子集菜单
	 List<MenuItem> menus=MenuProvider.getTopSubMenu(menuId);
	 StringBuffer buf=new StringBuffer();
	 for(MenuItem mi : menus){
		 appendMenuItem(mi,buf,true);
	 }
	 menuContent = buf.toString();
	 cacheMenuContent(menuContent);
	 return menuContent;
  }
  
  private static void appendMenuItem(MenuItem item,StringBuffer menuStr,boolean iconFlag){
	   if(item==null)
		   return;
	   menuStr.append("<li>");
	   String url=item.getPath();
	   String title=item.getName();
	   if(StringHelper.isEmptyByTrim(url)){
		   menuStr.append("<a href=\"javascript:;\">");
	   }else{
		   menuStr.append("<a href=\"").append(url.trim())
		   .append("\" rel=\"").append(item.getId())
		   .append("\" target=\"cssTab\"	title=\"")
		   .append(title).append("\" refresh=\"true\">");		 
	   }
	   if(iconFlag){
		   String icon = item.getIcon();
		   menuStr.append("<i class=\"").append(icon!=null?icon:"").append("\"></i>");
	   }
	   menuStr.append("<span class=\"title\">").append(title!=null?title:"").append("</span>");
	   List<MenuItem> items=item.getMenus();
	   if(items!=null && items.size()>0)
	   menuStr.append("<span class=\"arrow\"></span>");	   
	   menuStr.append("</a>");
	   if(items!=null && items.size()>0){
		   menuStr.append("<ul  class=\"sub-menu\">");
		   for(MenuItem mi : items){
			   appendMenuItem(mi,menuStr,false);
		   }
		   menuStr.append("</ul>");
	   }
	   menuStr.append("</li>");
  }  
  
   /**
	 * 从缓存中获取用户菜单
	 * @return
	 */
	private static String  getCachedMenuContent(){
		IUser user =UserQueryProvider.currentUser();
		if(user==null)return null;
		return (String)com.css.db.memcached.MemCachedFactory.get(cacheName+user.getUserId());
	}	
	/**
	 * 缓存用户菜单
	 * @return
	 */
	private static void cacheMenuContent(String content){
		if(content==null)
			return;
		IUser user =UserQueryProvider.currentUser();
		if(user==null)
			return ;
		com.css.db.memcached.MemCachedFactory.set(cacheName+user.getUserId(),content,ConfigurationManager.getCacheTime());
	}
}